package br.ufpe.cin.rva;

/************************************************************************\
 * http://jeffchien.com/2013/04/22/leap-motion-space-shooter-game/#comment-4
 * Copyright (C) 2012-2013 Leap Motion, Inc. All rights reserved.        *
 * Leap Motion proprietary and confidential. Not for distribution.       *
 * Use subject to the terms of the Leap Motion SDK Agreement available at*
 * https://developer.leapmotion.com/sdk_agreement, or another agreement  *
 * between Leap Motion and you, your company or other organization.      *
 \***********************************************************************/
 
import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

import org.newdawn.slick.SlickException;

import com.leapmotion.leap.Controller;
import com.leapmotion.leap.Finger;
import com.leapmotion.leap.FingerList;
import com.leapmotion.leap.Frame;
import com.leapmotion.leap.Hand;
import com.leapmotion.leap.Listener;
import com.leapmotion.leap.Vector;
// Get the most recent frame and report some basic information
// Get the first hand
// Check if the hand has any fingers
// Calculate the hand's average finger tip position
// add the position vectors up for each finger
// scale the x position to the game resolution
// z-axis value for the laser
// scale the y position to the game resolution
// Create a sample listener and controller
// Have the sample listener receive events from the controller
// Keep this process running until Enter is pressed
// Remove the sample listener when done
class SampleListener2 extends Listener {
	public static float pontoToque = 160;
	boolean pressionado, anterior;
	MakeSound3 makeSound = new MakeSound3();
	
    public void onInit(Controller controller) {
        System.out.println("Initialized");
    }
 
    public void onConnect(Controller controller) {
        System.out.println("Connected");
 
    }
 
    public void onDisconnect(Controller controller) {
        System.out.println("Disconnected");
    }
 
    public void onExit(Controller controller) {
        System.out.println("Exited");
    }
 
    public void onFrame(Controller controller) {
        // Get the most recent frame and report some basic information
        Frame frame = controller.frame();
 
        if (!frame.hands().empty()) {
            // Get the first hand
            Hand hand = frame.hands().get(0);
 
            // Check if the hand has any fingers
            FingerList fingers = hand.fingers();
            Vector avgPos;
            if (!fingers.empty()) {
                // Calculate the hand's average finger tip position
                int i = 0;
                float x = 0, y = 0, z = 0;
                for (Finger finger : fingers) {
                    // add the position vectors up for each finger
                	avgPos = Vector.zero();
                    avgPos = avgPos.plus(finger.tipPosition());
                    // scale the x position to the game resolution
                    x = (((float) avgPos.getX()/2) + 100) * 5;
                    // z-axis value for the laser
                    y = (float) avgPos.getY();
                    // scale the y position to the game resolution
                    z = (((float) avgPos.getZ()/2) + 100) * 6;
                	if (y <= pontoToque) {
                		pressionado = true;
                	} else {
                		pressionado = false;
                	}
            		if((pressionado == true) && (false == anterior)){
            			makeSound.playSound("D:/DESENVOLVIMENTO/workspaceUFPE/PianoCrystal/res/beep.wav");
            			System.out.println("Tocou");
            		}
                	anterior = pressionado;
                }
            }
        }
 
    }
}
 
class TestLeap {
    public static void main(String[] args) throws SlickException {
 
        // Create a sample listener and controller
        SampleListener2 listener = new SampleListener2();
        Controller controller = new Controller();
        // Have the sample listener receive events from the controller
        controller.addListener(listener);
        // Keep this process running until Enter is pressed
        System.out.println("Press Enter to quit...");
        try {
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // Remove the sample listener when done
        controller.removeListener(listener);
    }
}

class MakeSound3 {
	public static boolean ativo;
    private final int BUFFER_SIZE = 128000;
    private File soundFile;
    private AudioInputStream audioStream;
    private AudioFormat audioFormat;
    private SourceDataLine sourceLine;

    /**
     * @param filename the name of the file that is going to be played
     */
    public void playSound(String filename){
    	if(!ativo){
    		
        String strFilename = filename;
        ativo = true;
        try {
            soundFile = new File(strFilename);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }

        try {
            audioStream = AudioSystem.getAudioInputStream(soundFile);
        } catch (Exception e){
            e.printStackTrace();
            System.exit(1);
        }

        audioFormat = audioStream.getFormat();

        DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
        try {
            sourceLine = (SourceDataLine) AudioSystem.getLine(info);
            sourceLine.open(audioFormat);
        } catch (LineUnavailableException e) {
            e.printStackTrace();
            System.exit(1);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }

        sourceLine.start();

        int nBytesRead = 0;
        byte[] abData = new byte[BUFFER_SIZE];
        while (nBytesRead != -1) {
            try {
                nBytesRead = audioStream.read(abData, 0, abData.length);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (nBytesRead >= 0) {
                @SuppressWarnings("unused")
                int nBytesWritten = sourceLine.write(abData, 0, nBytesRead);
            }
        }

        sourceLine.drain();
        sourceLine.close();
        ativo = false;
    	}
    }
}